import { useRef } from "react";
import { appStore } from "~/store";

export function useRequestWithTimeout(timeout: number = 10000) {
    const loadingRef = useRef<any>(null);
    let timeoutId: NodeJS.Timeout | null = null;

    const run = async <T>(
        requestFn: () => Promise<T>,
        onSuccess?: (res: T) => void,
        onError?: (err: any) => void
    ) => {
        try {
            loadingRef.current?.showLoading();

            // 启动超时定时器
            timeoutId = setTimeout(() => {
                loadingRef.current?.hideLoading();
                Toast.show({ content: appStore.app.language == 'zh' ? "操作超时，请稍后重试" : "Operation timed out, please try again later" });
                timeoutId = null;
            }, timeout);

            const res = await requestFn();

            // 如果超时已经触发，不再继续
            if (!timeoutId) return;

            clearTimeout(timeoutId);
            timeoutId = null;

            loadingRef.current?.hideLoading();
            onSuccess?.(res);
        } catch (err) {
            if (timeoutId) {
                clearTimeout(timeoutId);
                timeoutId = null;
            }
            loadingRef.current?.hideLoading();
            onError?.(err);
        }
    };

    return {
        loadingRef,
        run,
    };
}